package cn.itcast.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.itcast.pojo.EasyUIResult;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;

	@RequestMapping("user")
	@Controller("userController")
	public class UserController {
		
		/*@RequestMapping(value="users")
		public String toUsers(){
			
			return "users";
		}*/
		@RequestMapping("page/{pageName}")
		public String toPage(@PathVariable("pageName")String pageName){
			
			return pageName;
		}
		
		@Autowired
		private UserService userService;
		
		@RequestMapping("list")
		@ResponseBody
		public EasyUIResult queryUserList(@RequestParam("page")Integer page,@RequestParam("rows")Integer rows){
			EasyUIResult result = userService.queryEasyUIResult(page,rows);
			return result;
		}
		
		@RequestMapping("save")
		@ResponseBody
		public Map<String,Integer> addUser(User user){
			Map map = new HashMap<String,Integer>();
			try {
				Boolean flag = userService.addUser(user);
				if(flag){
					map.put("status",200 );
				}else{
					map.put("status", 500);
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("status", 500);
			}
			return map;
			
		}
		
		@RequestMapping("delete")
		@ResponseBody
		public Map<String,Integer> deleteUserById(@RequestParam("ids")Long[] ids){
			Map map = new HashMap<String,Integer>();
			try {
				Boolean flag = userService.deleteUserById(ids);
				if(flag){
					map.put("status",200 );
				}else{
					map.put("status", 500);
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("status", 500);
			}
			return map;
			}
		
		@RequestMapping("edit")
		@ResponseBody
		public Map<String,Integer> editUser(User user){
			Map map = new HashMap<String,Integer>();
			try {
				Boolean flag = userService.editUser(user);
				if(flag){
					map.put("status",200 );
				}else{
					map.put("status", 500);
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("status", 500);
			}
			return map;
			}
		
		@RequestMapping("export/excel")
		public String exportExcel(Model model,@RequestParam("page")Integer page,@RequestParam("rows")Integer rows){
			EasyUIResult result = userService.queryEasyUIResult(page,rows);
			model.addAttribute("userList", result.getRows());
			
			return "userExcelView";
		}
	}

